import { z } from "zod";
import { prisma } from '../../../service/mysql.js';
import { updateFundTags } from '../../../service/fund.js';

export default {
    api: "updateFundTags",
    name: "修改账务标签",
    description: "根据客户提供的信息为指定账务明细添加标签，比如：明细1添加餐饮标签。",
    requestSchema: z.object({
        id: z.number().describe("账务明细ID"),
        sourceTags: z.string().describe("待修改的标签信息，多个使用逗号分隔。"),
        targetTags: z.string().describe("修改目标的标签信息，多个使用逗号分隔。"),
    }),
    func: async ({ id, sourceTags, targetTags }, context) => {
        const transaction = await prisma.t_transaction.findUnique({
            where: {
                id: id,
            }
        });
        if (!transaction) {
            throw new Error(`未找到ID为 ${id} 的交易记录`);
        }

        const dbTags = transaction.tags.split(',');
        const beDeleteTags = sourceTags.split(',');
        const beAddedTags = targetTags.split(',');
        beDeleteTags.forEach(delTag => {
            if (dbTags.includes(delTag)) {
                dbTags.splice(dbTags.indexOf(delTag), 1);
            }
        });
        beAddedTags.forEach(addedTag => {
            if (!dbTags.includes(addedTag)) {
                dbTags.push(addedTag);
            }
        });

        await updateFundTags(id, context.book.id, context.user.id, dbTags);
        return `账务明细ID ${id} 成功修改 ${sourceTags} 为 ${targetTags}, 当前标签为 ${dbTags.join(',')}`;
    }
}